package com.hxh.wechat.util

import android.content.Context
import com.google.gson.JsonObject
import com.hxh.wechat.activity.ChatPageActivity
import com.hxh.wechat.activity.ContactActivity
import com.hxh.wechat.activity.Router
import com.hxh.wechat.constant.GlobalConstant
import com.hxh.wechat.model.DataContent
import com.hxh.wechat.model.Msg
import com.hxh.wechat.model.MsgActionEnum
import com.hxh.wechat.model.MsgType
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import okhttp3.*
import java.net.Socket
import java.util.*

class ClientSocket {

    companion object {
        private var socket: WebSocket? = null;
        fun initSocket(con: Context) {
            val client = OkHttpClient()
            val request = Request.Builder()
                .url("ws://${GlobalConstant.URL}:8088/ws")
//                .url("ws://192.168.43.35:8088/ws")
                .build()
            socket = client.newWebSocket(request, object : WebSocketListener() {
                override fun onOpen(webSocket: WebSocket, response: Response) {
                    // 连接已经打开
                    println("连接成功")
                    //第一次连接
                    var content = DataContent(
                        MsgActionEnum.CONNECT.type,
                        Msg(DBUtil.getUser(con)?.id, "", MsgType.TEXT.type, "", ""),
                        ""
                    )
                    chat(content);
                }

                override fun onMessage(webSocket: WebSocket, text: String) {
                    // 收到消息
                    println("Received message: $text")
                    GlobalScope.launch {
                        Router.receiveMsg(text)
                    }
                }

                override fun onClosed(webSocket: WebSocket, code: Int, reason: String) {
                    // 连接已关闭
                    println("断开连接")
                }

                override fun onFailure(webSocket: WebSocket, t: Throwable, response: Response?) {
                    // 连接失败
                    println("连接失败")
                    // Attempt to reconnect after a delay of 5 seconds
                    Timer().schedule(object : TimerTask() {
                        override fun run() {
                            initSocket(con)
                        }
                    }, 5000)
                }
            })
        }

        fun chat(msg: DataContent): Boolean {
            return socket!!.send(DBUtil.getGson().toJson(msg))
        }
    }
}